import { debounce } from './index';
import QRCode from 'weapp-qrcode';

// 二维码生成配置接口
export interface QRCodeConfig {
  text: string;
  width: number;
  height: number;
  colorDark: string;
  colorLight: string;
  correctLevel: 'L' | 'M' | 'Q' | 'H';
  quietZone: number;
}

// 错误纠正级别常量
const CORRECT_LEVEL: Record<'L' | 'M' | 'Q' | 'H', number> = {
  L: 1,
  M: 0,
  Q: 3,
  H: 2
};

// 获取错误纠正级别
function getCorrectLevel(level: 'L' | 'M' | 'Q' | 'H'): number {
  return CORRECT_LEVEL[level] || CORRECT_LEVEL.H;
}

// 二维码生成函数
export const generateQRCode = debounce((config: QRCodeConfig): Promise<string> => {
  return new Promise((resolve, reject) => {
    try {
      // 首先确保文本有效
      if (!config.text || config.text.trim() === '') {
        reject(new Error('QR code text cannot be empty'));
        return;
      }

      // 使用旧版 Canvas API 生成二维码
      // 这可能会有兼容性问题，但我们将尝试一下
      new QRCode({
        canvasId: 'qrCanvas',
        text: config.text,
        width: config.width,
        height: config.height,
        colorDark: config.colorDark,
        colorLight: config.colorLight,
        correctLevel: getCorrectLevel(config.correctLevel),
        quietZone: config.quietZone,
        callback: (e) => {
          // 处理特殊情况：如果错误消息包含 "ok"，则不视为错误
          if (e && typeof e === 'object' && e.errMsg && e.errMsg.indexOf('ok') === -1) {
            console.error('QRCode render error:', e);
            reject(e);
            return;
          }
          
          // weapp-qrcode 库有时会将成功信息作为错误回调，我们忽略这种情况
          if (e && typeof e === 'object' && e.errMsg && e.errMsg.indexOf('ok') !== -1) {
            console.log('QRCode render completed with "ok" message:', e.errMsg);
          }
          
          // 使用延迟和多次尝试来确保 canvas 已经绘制完成
          const attemptToExtractImage = (attempts = 0, maxAttempts = 5) => {
            wx.canvasToTempFilePath({
              canvasId: 'qrCanvas',
              success: (res) => {
                if (res && res.tempFilePath) {
                  console.log('成功生成二维码路径:', res.tempFilePath);
                  resolve(res.tempFilePath);
                } else if (attempts < maxAttempts) {
                  console.warn(`未获取到临时路径, 重试中 (${attempts + 1}/${maxAttempts})`);
                  setTimeout(() => attemptToExtractImage(attempts + 1, maxAttempts), 300);
                } else {
                  reject(new Error('Failed to extract QR code after multiple attempts'));
                }
              },
              fail: (err) => {
                console.error(`Canvas to temp file failed (attempt ${attempts + 1}/${maxAttempts}):`, err);
                if (attempts < maxAttempts) {
                  setTimeout(() => attemptToExtractImage(attempts + 1, maxAttempts), 300);
                } else {
                  reject(new Error('Failed to generate QR code after multiple attempts'));
                }
              },
              complete: () => {
                console.log(`完成二维码临时文件尝试 ${attempts + 1}/${maxAttempts}`);
              }
            });
          };
          
          // 给一定时间让 canvas 完成绘制
          setTimeout(() => attemptToExtractImage(), 500);
        }
      });
    } catch (e) {
      console.error('QRCode initialization error:', e);
      reject(e);
    }
  });
}, 300);

// 验证颜色格式
export const isValidColor = (color: string): boolean => {
  const colorRegex = /^#[0-9A-Fa-f]{6}$/;
  return colorRegex.test(color);
};

// 验证文本长度
export const isValidText = (text: string): boolean => {
  return text.length <= 500;
};

// 验证尺寸范围
export const isValidSize = (size: number): boolean => {
  return size >= 100 && size <= 1000;
}; 